package learn.basic;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.gephi.graph.api.GraphController;
import org.gephi.graph.api.GraphModel;
import org.gephi.io.exporter.api.ExportController;
import org.gephi.io.generator.plugin.RandomGraph;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.ContainerFactory;
import org.gephi.io.importer.api.ImportController;
import org.gephi.io.processor.plugin.DefaultProcessor;
import org.gephi.layout.plugin.AutoLayout;
import org.gephi.layout.plugin.force.StepDisplacement;
import org.gephi.layout.plugin.force.yifanHu.YifanHuLayout;
import org.gephi.project.api.ProjectController;
import org.gephi.project.api.Workspace;
import org.openide.util.Lookup;

public class ManipulateProjectAndWorkspace {

	public static void main(String[] args) {
		ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
		pc.newProject();
		final Workspace workspace1 = pc.getCurrentWorkspace();
		
		Container container = Lookup.getDefault().lookup(ContainerFactory.class).newContainer();
		RandomGraph randomGraph = new RandomGraph();
		randomGraph.setNumberOfNodes(500);
		randomGraph.setWiringProbability(0.005);
		randomGraph.generate(container.getLoader());
		
		ImportController importController = Lookup.getDefault().lookup(ImportController.class);
		importController.process(container, new DefaultProcessor(), workspace1);
		
		final Workspace workspace2 = pc.duplicateWorkspace(workspace1);
		
		ExecutorService executor = Executors.newFixedThreadPool(2);
		
		Future<?> f1 = executor.submit(createLayoutRunnable(workspace1));
		Future<?> f2 = executor.submit(createLayoutRunnable(workspace2));
		try {
			f1.get();
			f2.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		executor.shutdown();
		
		ExportController ec = Lookup.getDefault().lookup(ExportController.class);
		try {
			pc.openWorkspace(workspace1);
			ec.exportFile(new File("d://parallel_workspace1.pdf"));
			pc.openWorkspace(workspace2);
			ec.exportFile(new File("d://parallel_workspace2.pdf"));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
	}

	private static Runnable createLayoutRunnable(final Workspace workspace) {
		return new Runnable() {

			@Override
			public void run() {
				GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel(workspace);
				AutoLayout autoLayout = new AutoLayout(10, TimeUnit.SECONDS);
				autoLayout.setGraphModel(gm);
				autoLayout.addLayout(new YifanHuLayout(null, new StepDisplacement(1f)), 1f);
				autoLayout.execute();
			}};
	}

}